package com.github.bobjoy.java.classloader;

import com.github.bobjoy.java.classloader.loader.ClassLoaderA;
import com.github.bobjoy.java.classloader.loader.ClassLoaderB;

import org.junit.Test;

import sun.net.spi.nameservice.dns.DNSNameService;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClassLoaderDemo {

    @Test
    public void testDelegate() {
        System.out.println(String.class.getClassLoader());
        System.out.println(ClassLoaderDemo.class.getClassLoader());
        System.out.println(Test.class.getClassLoader());
        System.out.println(DNSNameService.class.getClassLoader());
    }

    @Test
    public void testVisible() {
        try {
            System.out.println(ClassLoaderDemo.class.getClassLoader());
            Class.forName("com.bfl.learning.classloader.ClassLoaderTest", true, ClassLoaderDemo.class.getClassLoader().getParent());
        } catch (ClassNotFoundException e) {
            Logger.getLogger(ClassLoaderDemo.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    @Test
    public void testUnique() {
        try {
            Class<?> ac = Class.forName("com.bfl.learning.classloader.A", true, new ClassLoaderA());
            Class<?> bc = Class.forName("com.bfl.learning.classloader.B", true, new ClassLoaderB());

            Object a = ac.newInstance();

            System.out.println(a.getClass().getClassLoader());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testIntegerCache() throws NoSuchFieldException, IllegalAccessException {

        Class<?> clazz = Integer.class.getDeclaredClasses()[0];
        for (Class cls : Integer.class.getDeclaredClasses()) {
            System.out.println(cls);
        }

        Field field = clazz.getDeclaredField("cache");
        field.setAccessible(true);

        Integer[] cache = (Integer[]) field.get(clazz);
        cache[132] = cache[133];
        for (Integer i : cache) {
            //System.out.println(i);
        }

        int a = 2;
        int b = a + a;
        System.out.printf("%d + %d = %d", a, a, b);

    }

}

